package org.example.nettydemo.netty.redis;

import io.netty.bootstrap.Bootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.net.InetSocketAddress;

/**
 * @author liujing
 */
public class RedisClient {
    static final Logger log = LoggerFactory.getLogger(RedisClient.class);
    public static void main(String[] args) {
        NioEventLoopGroup group =  new NioEventLoopGroup();
        try {
            ChannelFuture channelFuture = new Bootstrap()
                    .group(group)
                    .channel(NioSocketChannel.class)
                    .handler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel ch) {
                            // 打印日志
                            ch.pipeline().addLast(new LoggingHandler(LogLevel.DEBUG));
                            ch.pipeline().addLast(new ChannelInboundHandlerAdapter() {
                                @Override
                                public void channelActive(ChannelHandlerContext ctx) throws Exception {
                                    // 回车与换行符
                                    final byte[] LINE = {'\r','\n'};
                                    // 获得ByteBuf
                                    ByteBuf buffer = ctx.alloc().buffer();

                                    log.info("连接 Redis 成功，发送 AUTH 认证");
                                    // auth 888
                                    buffer.writeBytes("*2".getBytes());
                                    buffer.writeBytes(LINE);
                                    buffer.writeBytes("$4".getBytes());
                                    buffer.writeBytes(LINE);
                                    buffer.writeBytes("auth".getBytes());
                                    buffer.writeBytes(LINE);
                                    buffer.writeBytes("$11".getBytes());
                                    buffer.writeBytes(LINE);
                                    buffer.writeBytes("888".getBytes());
                                    buffer.writeBytes(LINE);

                                    // 连接建立后，向Redis中发送一条指令，注意添加回车与换行
                                    log.info("发送 SET 指令");
                                    // set name Nyima
                                    buffer.writeBytes("*3".getBytes());
                                    buffer.writeBytes(LINE);
                                    buffer.writeBytes("$3".getBytes());
                                    buffer.writeBytes(LINE);
                                    buffer.writeBytes("set".getBytes());
                                    buffer.writeBytes(LINE);
                                    buffer.writeBytes("$4".getBytes());
                                    buffer.writeBytes(LINE);
                                    buffer.writeBytes("name".getBytes());
                                    buffer.writeBytes(LINE);
                                    buffer.writeBytes("$5".getBytes());
                                    buffer.writeBytes(LINE);
                                    buffer.writeBytes("Nyima".getBytes());
                                    buffer.writeBytes(LINE);

                                    ctx.writeAndFlush(buffer);

                                }

                                @Override
                                public void channelRead(ChannelHandlerContext ctx, Object msg) {
//                                    ByteBuf buf = (ByteBuf) msg;
//                                    byte[] bytes = new byte[buf.readableBytes()];
//                                    buf.readBytes(bytes);
//                                    String response = new String(bytes);
//                                    log.info("Redis Response: {}", response);
//
//                                    // 回车与换行符
//                                    final byte[] LINE = {'\r','\n'};
//                                    // 获得ByteBuf
//                                    ByteBuf buffer = ctx.alloc().buffer();
//
//                                    // 标识是否认证成功
//                                    boolean authSuccess = false;
//                                    if (!authSuccess) {
//                                        if (response.startsWith("+OK")) {
//                                            log.info("Redis 认证成功，发送 SET 命令");
//                                            authSuccess = true;
//                                            // 连接建立后，向Redis中发送一条指令，注意添加回车与换行
//                                            log.info("发送 SET 指令");
//                                            // set name Nyima
//                                            buffer.writeBytes("*3".getBytes());
//                                            buffer.writeBytes(LINE);
//                                            buffer.writeBytes("$3".getBytes());
//                                            buffer.writeBytes(LINE);
//                                            buffer.writeBytes("set".getBytes());
//                                            buffer.writeBytes(LINE);
//                                            buffer.writeBytes("$4".getBytes());
//                                            buffer.writeBytes(LINE);
//                                            buffer.writeBytes("name".getBytes());
//                                            buffer.writeBytes(LINE);
//                                            buffer.writeBytes("$5".getBytes());
//                                            buffer.writeBytes(LINE);
//                                            buffer.writeBytes("Nyima".getBytes());
//                                            buffer.writeBytes(LINE);
//                                            ctx.writeAndFlush(buffer);
//                                        } else {
//                                            log.error("Redis 认证失败，关闭连接");
//                                            ctx.close();
//                                        }
//                                    } else {
//                                        log.info("SET 命令执行结果: {}", response);
//                                        ctx.close(); // 关闭连接
//                                    }
                                }

                            });
                        }
                    })
                    .connect(new InetSocketAddress("localhost", 6379));
            channelFuture.sync();
            // 关闭channel
            channelFuture.channel().close().sync();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            // 关闭group
            group.shutdownGracefully();
        }
    }
}
